/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#ifndef OBS_PLUGIN_RESOURCE_MANAGER_H
#define OBS_PLUGIN_RESOURCE_MANAGER_H
#include <map>
#include <mutex>
#include "Module/src/common/JsonHelper.h"

namespace OBSPlugin {
constexpr auto RESOURCE_MODULE = "ResourceManager";
class ResourceManager {
public:
    ResourceManager(const ResourceManager&) = delete;
    ResourceManager& operator=(const ResourceManager&) = delete;
    ResourceManager(ResourceManager&&) = delete;
    ResourceManager& operator=(ResourceManager&&) = delete;
    static ResourceManager& GetInstance()
    {
        static ResourceManager instance;
        return instance;
    }
    void Insert(const std::string& key)
    {
        HCP_Log(DEBUG, RESOURCE_MODULE) << "Enter  Insert" << HCPENDLOG;
        std::lock_guard<std::shared_mutex> lck(m_mtxLock);
        if (CheckKeyExist(key)) {
            return;
        }
        m_mainKeyMap.emplace(key, key);
        HCP_Log(INFO, RESOURCE_MODULE) << "Insert key:" << key << HCPENDLOG;
        return;
    }

    void Erase(const std::string& key)
    {
        HCP_Log(DEBUG, RESOURCE_MODULE) << "Enter Erase" << HCPENDLOG;
        std::lock_guard<std::shared_mutex> lck(m_mtxLock);
        if (!CheckKeyExist(key)) {
            return;
        }
        m_mainKeyMap.erase(key);
        HCP_Log(INFO, RESOURCE_MODULE) << "Erase key:" << key << HCPENDLOG;
        return;
    }

    void Clear(const std::string& key)
    {
        HCP_Log(DEBUG, RESOURCE_MODULE) << "Clear key:" << key << HCPENDLOG;
        std::lock_guard<std::shared_mutex> lck(m_mtxLock);
        m_mainKeyMap.clear();
    }
    bool CheckKeyExist(const std::string &key)
    {
        return m_mainKeyMap.count(key) != 0;
    }
    int GetKeyCount()
    {
        for (auto key : m_mainKeyMap) {
            HCP_Log(INFO, RESOURCE_MODULE) << "Get key:" << key.first << HCPENDLOG;
        }
        return m_mainKeyMap.size();
    }
private:
    ResourceManager() = default;
    ~ResourceManager() noexcept {};

private:
    std::shared_mutex m_mtxLock {};                     /* mutex lock */
    std::map<std::string, std::string> m_mainKeyMap {};  /* key info */
};
}

#endif